﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LibraryMusicStore;

namespace AppMusicStore
{
    public partial class frmReport : DevExpress.XtraEditors.XtraForm
    {
        IRepository<Album> albumRepository;
        IRepository<Receipt> receiptRepository;
        IRepository<Issue> issueRepository;
        IRepository<Genre> genreRepository;
        IRepository<IssueDetail> issueDetailRep;
        DataTable dt;

        public frmReport()
        {
            InitializeComponent();
        }

        private void frmNumberOfProductsInStockByDate_Load(object sender, EventArgs e)
        {
            try
            {
                Init();

                RetrieveData();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void Init()
        {
            albumRepository = new Repository<Album>();
            receiptRepository = new Repository<Receipt>(albumRepository.GetContext());
            issueRepository = new Repository<Issue>(albumRepository.GetContext());
            genreRepository = new Repository<Genre>(albumRepository.GetContext());
            issueDetailRep = new Repository<IssueDetail>(issueRepository.GetContext());

            lblNumber.Text = "";
            lblTotal.Text = "";

            dateEdit1.DateTime = DateTime.Now;
            dateFrom.DateTime = DateTime.Now;
            dateTo.DateTime = DateTime.Now;

            calcFrom.EditValue = 0;
            calcTo.EditValue = 0;

            layoutNumberGroup.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;

            gridControl1.DataSource = CreateDataTable();
        }

        private DataTable CreateDataTable()
        {
            dt = new DataTable("Sold");
            dt.BeginInit();
            dt.Columns.Add("Id", System.Type.GetType("System.Int32"));
            dt.Columns.Add("Title", System.Type.GetType("System.String"));
            dt.Columns.Add("Price", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("QuantitySold", System.Type.GetType("System.Int32"));
            
            dt.EndInit();
            return dt;
        }

        private void RetrieveData()
        {
            try
            {
                //lookup album
                bindingSourceAlbum.DataSource = albumRepository.GetAll()
                    .OrderByDescending(a => a.AlbumId)
                    .Where(a => a.Deleted == null || a.Deleted == false);
                lupAlbum.ItemIndex = 0;

                //lookup genre
                bindingSourceGenre.DataSource = genreRepository.GetAll()
                    .OrderByDescending(g => g.GenreId);
                lupGenre.ItemIndex = 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            //view number of products in stock by date
            try
            {
                this.ValidateChildren();

                if (ErrorProvider1.HasErrors)
                {
                    foreach (var item in ErrorProvider1.GetControlsWithError())
                    {
                        item.Focus();
                        Common.ShowErrorBox(ErrorProvider1.GetError(item));
                        return;
                    }
                }

                int nhap = 0, xuat = 0;

                var receipts = receiptRepository.Where(r => 
                    r.ReceiptDate.Date <= dateEdit1.DateTime.Date);

                var issues = issueRepository.Where(i =>
                    i.IssueDate.Date <= dateEdit1.DateTime.Date);
                
                foreach (var receipt in receipts)
                {
                    nhap += (from rd in receipt.ReceiptDetails
                             where rd.AlbumId == Convert.ToInt32(lupAlbum.EditValue)
                             select rd.Quantity).Sum();
                }

                foreach (var issue in issues)
                {
                    xuat += (from iD in issue.IssueDetails
                             where iD.AlbumId == Convert.ToInt32(lupAlbum.EditValue)
                             select iD.Quantity).Sum();
                }

                lblNumber.Text = "Tồn kho : " + (nhap - xuat).ToString();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                btnView.PerformClick();
                
                var frm = new frmPreview();
                frm.String1 = lupAlbum.Text + ". " + lblNumber.Text;
                frm.String2 = dateEdit1.Text;
                frm.Show();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void Check(object sender, CancelEventArgs e)
        {
            string str = null;

            //title required
            if (sender.GetType().Name == "DateEdit")
            {
                DateEdit de = (DateEdit)sender;
                if (de.Text.Trim().Length == 0)
                    str = "Chưa nhập ngày";
            }
            if (sender.GetType() == typeof(LookUpEdit))
            {
                var lup = sender as LookUpEdit;
                if (lup.EditValue == null)
                    str = "Chưa chọn album";
            }
            ErrorProvider1.SetIconAlignment((Control)sender, ErrorIconAlignment.MiddleRight);
            ErrorProvider1.SetError((Control)sender, str);
        }

        private void btnView2_Click(object sender, EventArgs e)
        {
            try
            {
                lblTotal.Text = "";
                dt.Clear();

                var issueDetailQuery = issueDetailRep.Where(iD =>
                        iD.Issue.IssueDate.Date >= dateFrom.DateTime.Date &&
                        iD.Issue.IssueDate.Date <= dateTo.DateTime.Date);

                if (radioGroup1.SelectedIndex == 0)
                {
                    var groupQuery = from issueDetail in issueDetailQuery
                                     where issueDetail.Album.GenreId == Convert.ToInt32(lupGenre.EditValue)
                                     group issueDetail by issueDetail.AlbumId into g
                                     select new
                                     {
                                         g.Key,
                                         sumQuantity = g.Sum(issueDetail =>
                                             issueDetail.Quantity)
                                     };

                    foreach (var item in groupQuery)
                    {
                        DataRow row = dt.NewRow();

                        var t = albumRepository.GetById(item.Key);

                        row["Id"] = t.AlbumId;
                        row["Title"] = t.Title;
                        row["Price"] = t.Price;
                        row["QuantitySold"] = item.sumQuantity;

                        dt.Rows.Add(row);
                    }
                    dt.AcceptChanges();
                }
                else
                {
                    var groupQuery = (from issueDetail in issueDetailQuery
                                      group issueDetail by issueDetail.AlbumId into g
                                      select new
                                      {
                                          g.Key,
                                          sumQuantity = g.Sum(issueDetail =>
                                              issueDetail.Quantity)
                                      }).Where(g =>
                                          (Convert.ToInt32(calcTo.EditValue) == 0 ||
                                          g.sumQuantity <= Convert.ToInt32(calcTo.EditValue))
                                          &&
                                          g.sumQuantity >= Convert.ToInt32(calcFrom.EditValue));

                    foreach (var item in groupQuery)
                    {
                        DataRow row = dt.NewRow();

                        var t = albumRepository.GetById(item.Key);

                        row["Id"] = t.AlbumId;
                        row["Title"] = t.Title;
                        row["Price"] = t.Price;
                        row["QuantitySold"] = item.sumQuantity;

                        dt.Rows.Add(row);
                    }
                    dt.AcceptChanges();
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void btnPrint2_Click(object sender, EventArgs e)
        {
            try
            {
                btnView2.PerformClick();
                if (dt.Rows.Count == 0)
                {
                    Common.ShowErrorBox("Không có dữ liệu");
                    return;
                }

                var frm = new frmPreview();
                frm.Count = Convert.ToInt32(gridView1.Columns["Id"].SummaryItem.SummaryValue);
                frm.Sum = Convert.ToInt32(gridView1.Columns["QuantitySold"].SummaryItem.SummaryValue);
                if (radioGroup1.SelectedIndex == 0)
                    frm.String1 = " loại :" + lupGenre.Text;
                else
                    if (Convert.ToInt32(calcTo.EditValue) == 0)
                        frm.String1 = " số lượng" + " : lớn hơn hoặc bằng " + calcFrom.EditValue;
                    else if ( Convert.ToInt32(calcFrom.EditValue) <= 0)
                        frm.String1 = " số lượng" + " : nhỏ hơn hoặc bằng " + calcTo.EditValue;
                    else frm.String1 = " số lượng" + " : " + calcFrom.EditValue + " đến " + calcTo.EditValue;
                frm.String2 = dateFrom.Text + " đến " + dateTo.Text;
                frm.dt = dt;
                frm.Show();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                lblTotal.Text = "";
                dt.Clear();

                if (radioGroup1.SelectedIndex == 0)
                {
                    layoutNumberGroup.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    layoutGenre.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                }
                else
                {
                    layoutNumberGroup.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    layoutGenre.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }
    }
}